package com.emergency.embackend.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.emergency.embackend.dto.UserDTO;
import com.emergency.embackend.entity.SysUser;
import com.emergency.embackend.exception.EmException;
import com.emergency.embackend.mapper.SysUserMapper;
import com.emergency.embackend.service.SysUserService;
import com.emergency.embackend.utils.JWTUtils;
import com.emergency.embackend.utils.RedisConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public String login(String username, String password) {
        SysUser sysUser = sysUserMapper.login(username, password);
        if(sysUser==null){
            throw new EmException("401","账号或密码错误");
        }
        String res;
        //保存用户到redis中,这里要以随机的token为key
        // 使用hash数据类型来存储用户数据
        //随机生成token，作为登陆令牌
        String token = JWTUtils.getJwtToken(sysUser.getId(),sysUser.getUsername());
        //将User对象转换为Hash存储
        UserDTO userDTO = BeanUtil.copyProperties(sysUser, UserDTO.class);
        userDTO.setIcon(" ");
        userDTO.setNickName(" ");
        //解决long类型和String类型之间的转换，因为id是long类型
        Map<String,Object> map= BeanUtil.beanToMap(userDTO,new HashMap<>(),
                CopyOptions.create().setIgnoreNullValue(true).setFieldValueEditor((fieldName, fieldValue)->fieldValue.toString()));
        stringRedisTemplate.opsForHash().putAll(RedisConstants.LOGIN_USER_KEY+token,map);
        stringRedisTemplate.expire(RedisConstants.LOGIN_USER_KEY+token,RedisConstants.LOGIN_TOKEN_TTL, TimeUnit.SECONDS);
        res = token;
        return res;
    }
}